/*
Copyright [2020] [https://www.xiaonuo.vip]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：

1.请不要删除和修改根目录下的LICENSE文件。
2.请不要删除和修改Snowy源码头部的版权声明。
3.请保留源码和相关描述文件的项目出处，作者声明等。
4.分发源码时候，请注明软件出处 https://gitee.com/xiaonuobase/snowy
5.在修改包名，模块名称，项目代码等时，请注明软件出处 https://gitee.com/xiaonuobase/snowy
6.若您的项目无法满足以上几点，可申请商业授权，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.modular.upGradingBusiness.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import vip.xiaonuo.core.context.login.LoginContextHolder;
import vip.xiaonuo.core.exception.ServiceException;
import vip.xiaonuo.core.factory.PageFactory;
import vip.xiaonuo.core.pojo.login.SysLoginUser;
import vip.xiaonuo.core.pojo.page.PageResult;
import vip.xiaonuo.core.util.PoiUtil;
import vip.xiaonuo.modular.upGradingBusiness.dto.UpgradingBusinessOrderDto;
import vip.xiaonuo.modular.upGradingBusiness.entity.UpgradingBusinessOrder;
import vip.xiaonuo.modular.upGradingBusiness.enums.UpgradingBusinessOrderExceptionEnum;
import vip.xiaonuo.modular.upGradingBusiness.mapper.UpgradingBusinessOrderMapper;
import vip.xiaonuo.modular.upGradingBusiness.param.UpgradingBusinessOrderParam;
import vip.xiaonuo.modular.upGradingBusiness.service.UpgradingBusinessOrderService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.modular.upGradingBusiness.BusinessConst;
import vip.xiaonuo.modular.util.HttpClientService;
import vip.xiaonuo.sys.modular.org.entity.SysOrg;
import vip.xiaonuo.sys.modular.org.service.SysOrgService;
import vip.xiaonuo.sys.modular.user.entity.SysUserDataScope;
import vip.xiaonuo.sys.modular.user.service.SysUserDataScopeService;
import vip.xiaonuo.sys.modular.user.service.SysUserService;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 套餐升档（外呼）订单service接口实现类
 *
 * @author herrywong
 * @date 2022-02-13 12:00:13
 */
@Service
public class UpgradingBusinessOrderServiceImpl extends ServiceImpl<UpgradingBusinessOrderMapper, UpgradingBusinessOrder> implements UpgradingBusinessOrderService {

    @Autowired
    SysUserDataScopeService dataScopeService;

    @Autowired
    SysOrgService orgService;

    @Autowired
    SysUserService userService;

    @Override
    public PageResult<UpgradingBusinessOrderDto> page(UpgradingBusinessOrderParam upgradingBusinessOrderParam) {
        QueryWrapper<UpgradingBusinessOrder> queryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotNull(upgradingBusinessOrderParam)) {

            // 根据 查询
            if (ObjectUtil.isNotEmpty(upgradingBusinessOrderParam.getArea())) {
                queryWrapper.lambda().like(UpgradingBusinessOrder::getArea, upgradingBusinessOrderParam.getArea());
            }
            if (ObjectUtil.isNotEmpty(upgradingBusinessOrderParam.getStatus())) {
                queryWrapper.lambda().like(UpgradingBusinessOrder::getStatus, upgradingBusinessOrderParam.getStatus());
            }
            if (ObjectUtil.isNotEmpty(upgradingBusinessOrderParam.getKeyword())) {
                queryWrapper.lambda().like(UpgradingBusinessOrder::getKeyword, upgradingBusinessOrderParam.getKeyword());
            }
            // 根据 查询
            if (ObjectUtil.isNotEmpty(upgradingBusinessOrderParam.getCode())) {
                queryWrapper.lambda().like(UpgradingBusinessOrder::getCode, upgradingBusinessOrderParam.getCode());
            }
            // 根据 查询
            if (ObjectUtil.isNotEmpty(upgradingBusinessOrderParam.getDept())) {
                queryWrapper.lambda().eq(UpgradingBusinessOrder::getDept, upgradingBusinessOrderParam.getDept());
            }
            if (ObjectUtil.isNotEmpty(upgradingBusinessOrderParam.getSearchBeginTime())) {
                queryWrapper.lambda().between(
                        UpgradingBusinessOrder::getCreateTime,
                        upgradingBusinessOrderParam.getSearchBeginTime(),
                        upgradingBusinessOrderParam.getSearchEndTime());
            }
            // 根据 查询
            if (ObjectUtil.isNotEmpty(upgradingBusinessOrderParam.getMark())) {
                queryWrapper.lambda().like(UpgradingBusinessOrder::getMark, upgradingBusinessOrderParam.getMark());
            }
            // 根据 查询
            if (ObjectUtil.isNotEmpty(upgradingBusinessOrderParam.getPhone())) {
                queryWrapper.lambda().like(UpgradingBusinessOrder::getPhone, upgradingBusinessOrderParam.getPhone());
            }
            queryWrapper.lambda().orderByDesc(UpgradingBusinessOrder::getCreateTime);
            if (!LoginContextHolder.me().isSuperAdmin() && !LoginContextHolder.me().hasAnyRole("manager")) {
                queryWrapper.lambda().eq(UpgradingBusinessOrder::getCreateUser, LoginContextHolder.me().getSysLoginUser().getId());
            }
        }
        Page<UpgradingBusinessOrder> page = this.page(PageFactory.defaultPage(), queryWrapper);
        PageResult<UpgradingBusinessOrderDto> objectPageResult = new PageResult<>();
        List<UpgradingBusinessOrderDto> collect = page.getRecords().stream().map(item -> {
            UpgradingBusinessOrderDto dto = new UpgradingBusinessOrderDto();
            BeanUtils.copyProperties(item, dto);
            dto.setSysUser(userService.getUserById(item.getCreateUser()));
            return dto;
        }).collect(Collectors.toList());
        objectPageResult.setRows(collect);
        objectPageResult.setTotalRows(Convert.toInt(page.getTotal()));
        objectPageResult.setPageNo(Convert.toInt(page.getCurrent()));
        objectPageResult.setPageSize(Convert.toInt(page.getSize()));
        objectPageResult.setTotalPage(Convert.toInt(page.getPages()));

        return objectPageResult;
    }

    @Override
    public List<UpgradingBusinessOrder> list(UpgradingBusinessOrderParam upgradingBusinessOrderParam) {
        return this.list();
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public Object add(UpgradingBusinessOrderParam upgradingBusinessOrderParam) {
        String url = "https://wap.gd.10086.cn/businessHsh/hshShop/feeset/commodityOrder/handle.jsps?";
        StringBuilder urlBuilder = new StringBuilder(url);
        urlBuilder.append(BusinessConst.JSON_CALL_BACK.name).append("=").append(BusinessConst.JSON_CALL_BACK.value).append("&");
        urlBuilder.append("commCode").append("=").append(upgradingBusinessOrderParam.getCode()).append("&");
        urlBuilder.append("merchantCode=merchantCode&");
        urlBuilder.append("mobile").append("=").append(upgradingBusinessOrderParam.getPhone()).append("&");
        urlBuilder.append("inputCode").append("=").append(upgradingBusinessOrderParam.getValidateCode()).append("&");
        urlBuilder.append("jNumber=pBP4DipyBJNxDAfRuG9xBw%3D%3D&");
        urlBuilder.append("transtype=2&");
        Object result;
        try {
            result = HttpClientService.sendGet(urlBuilder.toString(), null);
        }catch (Exception e) {
            log.error("/businessHandling/getValidateCode", e);
            throw new ServiceException(400, "办理套餐失败");
        }
        String resultStr = (String) result;
        if (StringUtils.isNotEmpty(resultStr)) {
            resultStr = resultStr.replace(BusinessConst.JSON_CALL_BACK.value + "(", "");
            resultStr = resultStr.substring(0, resultStr.length() - 1);
        }
        JSONObject jsonObject = JSON.parseObject(resultStr);
        UpgradingBusinessOrder upgradingBusinessOrder = new UpgradingBusinessOrder();
        BeanUtil.copyProperties(upgradingBusinessOrderParam, upgradingBusinessOrder);
        String retCodeString = jsonObject.getString("retcode");
        if (!StringUtils.isNotEmpty(retCodeString)) {
            throw new ServiceException(400, "提交套餐失败，返回码为空");
        }
        int retCode = Integer.parseInt(retCodeString);
        if (retCode != 0) {
            upgradingBusinessOrder.setStatus(0);
        }else {
            upgradingBusinessOrder.setStatus(1);
        }
        StringBuilder keyWordBuilder = new StringBuilder();
        SysLoginUser sysLoginUser = LoginContextHolder.me().getSysLoginUser();
        keyWordBuilder.append(sysLoginUser.getName());
        for (Long dataScope : sysLoginUser.getDataScopes()) {
            SysUserDataScope scope = dataScopeService.getById(dataScope);
            if (Objects.isNull(scope)) {
                continue;
            }
            SysOrg org = orgService.getById(scope.getOrgId());
            if (Objects.isNull(org)) {
                continue;
            }
            keyWordBuilder.append(org.getName());
        }
        keyWordBuilder.append(upgradingBusinessOrderParam.getName());
        keyWordBuilder.append(upgradingBusinessOrderParam.getArea());
        keyWordBuilder.append(upgradingBusinessOrderParam.getPhone());
        upgradingBusinessOrder.setKeyword(keyWordBuilder.toString());
        this.save(upgradingBusinessOrder);
        return jsonObject;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<UpgradingBusinessOrderParam> upgradingBusinessOrderParamList) {
        upgradingBusinessOrderParamList.forEach(upgradingBusinessOrderParam -> {
            this.removeById(upgradingBusinessOrderParam.getId());
        });
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(UpgradingBusinessOrderParam upgradingBusinessOrderParam) {
        UpgradingBusinessOrder upgradingBusinessOrder = this.queryUpgradingBusinessOrder(upgradingBusinessOrderParam);
        BeanUtil.copyProperties(upgradingBusinessOrderParam, upgradingBusinessOrder);
        this.updateById(upgradingBusinessOrder);
    }

    @Override
    public UpgradingBusinessOrder detail(UpgradingBusinessOrderParam upgradingBusinessOrderParam) {
        return this.queryUpgradingBusinessOrder(upgradingBusinessOrderParam);
    }

    /**
     * 获取套餐升档（外呼）订单
     *
     * @author herrywong
     * @date 2022-02-13 12:00:13
     */
    private UpgradingBusinessOrder queryUpgradingBusinessOrder(UpgradingBusinessOrderParam upgradingBusinessOrderParam) {
        UpgradingBusinessOrder upgradingBusinessOrder = this.getById(upgradingBusinessOrderParam.getId());
        if (ObjectUtil.isNull(upgradingBusinessOrder)) {
            throw new ServiceException(UpgradingBusinessOrderExceptionEnum.NOT_EXIST);
        }
        return upgradingBusinessOrder;
    }

    @Override
    public void export(UpgradingBusinessOrderParam upgradingBusinessOrderParam) {
        List<UpgradingBusinessOrder> list = this.list(upgradingBusinessOrderParam);
        PoiUtil.exportExcelWithStream("SnowyUpgradingBusinessOrder.xls", UpgradingBusinessOrder.class, list);
    }

}
